import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

import router from '../router';
import qs from 'qs'
import { Session } from './storage';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
//const BASEURL = process.env.NODE_ENV === "production" ? 'http://java-api.suntaeiv.com:8080/chassis/chassis' : '/chassis';
const BASEURL = "http://47.105.39.99:9909"
//const BASEURL = "http://192.168.0.128:9909"// 配置新建一个 axios 实例
const service = axios.create({
    baseURL: BASEURL,
    timeout: 50000,
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么 token
        const sign = Session.get('sign');
        config.headers['sign'] = sign
        if (config.url === '/order/export') {
            config.responseType = 'blob'
        }
        let data = config.data || (config['data'] = []);
        config.data = qs.stringify(data)
        return config;


    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
let isReFreshPadding = true;
service.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        const res = response.data;
        if (response.config.url === '/order/export') {
            return res
        }
        if (isReFreshPadding) {
            if (response.data.code == -9999 || response.data.code == -9998) {
                isReFreshPadding = false;
                ElMessage.error(res["message"])
                Session.remove("token")
                router.push({
                    path: "/login"
                })
                localStorage.clear()
                window.location.reload();
            }
        }
        if (res.code == -1) {
            isReFreshPadding = true;
            ElMessage.error(res["msg"])
            return res
        }
        if (res.code == 0) {
            isReFreshPadding = true;
            return res
        }

    },
    (error) => {
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') != -1) {
            ElMessage.error('网络超时');
        } else if (error.message == 'Network Error') {
            ElMessage.error('网络连接错误');
        }
        return Promise.reject(error);
    }
);

// 导出 axios 实例
export default service;